package me.servlet;

import me.domain.Admin;
import me.service.AdminService;
import me.service.impl.AdminServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 管理登录页面的servlet
 *
 * @author Rainh
 */

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {

    //实例化adminService对象
//    private AdminService adminService = new AdminServiceImpl();
    //使用工厂创建adminService对象
//    private AdminService adminService = FactoryServiceImpl.getInstance().createAdminService();
    //通过工厂类获取adminService对象 使用多例  如果需要单例需要写在方法内部
//    private AdminService adminService = (AdminService)Factory.getBeans("adminService");

    //通过spring容器获取容器对象
    ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");
    //通过容器获取studentDao对象
    AdminService adminService = ac.getBean("adminService", AdminServiceImpl.class);

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //获取账号和密码
        String account = request.getParameter("account");
        String password = request.getParameter("password");
        //将账号和密码封装成Admin对象
        Admin admin = new Admin(account,password);
        //通过adminService的方法调用是否存在这样的一个账号和密码
        boolean exist = adminService.exist(admin);
        if(exist) {
            //如果存在，将admin信息存入session中
            request.getSession().setAttribute("ADMIN_PERMISSION",admin);
            //转发到首页
            request.getRequestDispatcher("indexServlet").forward(request,response);

        } else{
            //如果不存在，跳转到错误页面，并且提示信息
            request.getRequestDispatcher("error.jsp").forward(request,response);
        }

    }
}
